//
//  FSHomeViewController.m
//  FSiOSClient
//
//  Created by purlible on 2024/8/22.
//

#import "FSHomeViewController.h"
#import "FSHomeViewController+BluetoothList.h"
#import "FSHomeViewController+BluetoothData.h"
#import <WebKit/WebKit.h>
#import <JavaScriptCore/JavaScriptCore.h>

@interface WeakWebViewScriptMessageDelegate : NSObject<WKScriptMessageHandler>

@property (nonatomic, weak) id<WKScriptMessageHandler> scriptDelegate;

- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate;

@end

@implementation WeakWebViewScriptMessageDelegate

- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate {
    self = [super init];
    if (self) {
        _scriptDelegate = scriptDelegate;
    }
    return self;
}

#pragma mark - WKScriptMessageHandler
//遵循WKScriptMessageHandler协议，必须实现如下方法，然后把方法向外传递
//通过接收JS传出消息的name进行捕捉的回调方法

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    
    if ([self.scriptDelegate respondsToSelector:@selector(userContentController:didReceiveScriptMessage:)]) {
        [self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
    }
}


@end

@interface FSHomeViewController ()<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate>

@end

@implementation FSHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.deviceModel = [[FSRecordModel alloc] init];
    [self initWebView];
    [self initTableView];
    [self initBabyBluetooth];
}

- (void)initWebView
{
    self.view.backgroundColor = UIColorHex(0xEEEEEE);
    UIImageView * naviBgView = [[UIImageView alloc] init];
    naviBgView.image = [UIImage imageNamed:@"navi_bg"];
    [self.view addSubview:naviBgView];
    [naviBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.scale_offset(0);
        make.height.scale_equalTo(260);
    }];
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];

    WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc] initWithDelegate:self];
    
    WKUserContentController * wkUController = [[WKUserContentController alloc] init];
    [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"connectbt"];
    [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"getbtlist"];
    [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"getSystemLanguage"];
    [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"send"];
    
    config.userContentController = wkUController;
    
    //以下代码适配文本大小
    NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
    
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [config.userContentController addUserScript:wkUScript];

    CGFloat wk_h = SCREEN_HEIGHT - APPLICATION_STATUS_BAR_HEIGHT - APPLICATION_STATUS_INDICATOR_HEIGHT;
    
    WKWebView *webview = ({
        WKWebView *wk = [[WKWebView alloc] initWithFrame:CGRectMake(0, APPLICATION_STATUS_BAR_HEIGHT, SCREEN_WIDTH, wk_h) configuration:config];
        wk.backgroundColor = UIColor.clearColor;
        wk.scrollView.showsHorizontalScrollIndicator = NO;
        wk.scrollView.scrollEnabled = YES;
        wk.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        wk.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
        wk.allowsBackForwardNavigationGestures = YES;
        wk.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, wk_h);
        wk.navigationDelegate = self;
        wk.UIDelegate = self;
        wk.opaque = NO;
        wk;
    });
    [self.view addSubview:webview];
    [webview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(APPLICATION_STATUS_BAR_HEIGHT);
        make.left.right.equalTo(self.view);
        make.bottom.offset(-APPLICATION_STATUS_INDICATOR_HEIGHT);
    }];
    self.webView = webview;
    
    [self loadLocalHtml];
    
    
//    NSString *temp = [self getFullDataProtocolTwoWithCmd:@"7704" func:@"00"];
//    
//    DDLogDebug(@"组装的值 %@",temp);
}

#pragma mark- 将本地dist文件放入缓存
- (void)loadLocalHtml
{
    NSString *path=[[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"dist"];
    [FSTools copySandboxFile:path completion:^(BOOL success, NSString *destinationPath) {
        self.baseURL=destinationPath;
        [self loadLocalHtmlBaseURL:destinationPath];
    }];
}

#pragma mark-加载本地html
- (void)loadLocalHtmlBaseURL:(NSString *)baseURL
{
    NSString *htmlPath=baseURL;
    NSString *para=@"dist/index.html";
    NSURL *url=[NSURL URLWithString:para relativeToURL:[NSURL fileURLWithPath:htmlPath]];
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    DDLogDebug(@"网页开始加载");
    
    [self beginScanForPeripherals];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    DDLogDebug(@"网页加载完成");
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    DDLogDebug(@"网页加载失败: %@", error.localizedDescription);
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    
    if ([message.name isEqualToString:@"connectbt"])
    {
//        NSArray *body = message.body;
//        if(!body) return;
//        
//        if ([body isKindOfClass:[NSArray class]])
//        {
//            if (body.count > 0)
//            {
//                NSString * code = [[body firstObject] toString];
//                [self connectBluetoothAccrodingPeripheralName:code];
//            }
//        }
        
        NSString *body = (NSString *)message.body;
        if (isNull(body) || body.length == 0) return;
        
        [self connectBluetoothAccrodingPeripheralName:body];
    }
    else if ([message.name isEqualToString:@"getbtlist"])
    {
        DDLogDebug(@"js主动拉取蓝牙列表");
        [self updateH5BluetoothList];
    }
    else if ([message.name isEqualToString:@"getSystemLanguage"])
    {
        NSArray *langArr1 = [[NSUserDefaults standardUserDefaults] valueForKey:@"AppleLanguages"];
        NSString *language_key = langArr1.firstObject;
        NSString *language_value = @"0";
        
        if ([language_key isEqualToString:@"zh-Hans-CN"]) //中文简体
        {
            language_value = @"1";
        }
        else if ([language_key isEqualToString:@"zh-Hant-HK"]) //中文繁体
        {
            language_value = @"2";
        }
        else if ([language_key isEqualToString:@"en-CN"]) //英文
        {
            language_value = @"3";
        }
        else if ([language_key isEqualToString:@"fr-CN"]) //法国
        {
            language_value = @"4";
        }
        else if ([language_key isEqualToString:@"es-CN"]) //西班牙
        {
            language_value = @"5";
        }
        else if ([language_key isEqualToString:@"ru-CN"]) //俄罗斯
        {
            language_value = @"6";
        }
                
        NSString *receiveJS = [NSString stringWithFormat:@"window.initSystemLanguage('%@')",language_value];
        [self.webView evaluateJavaScript:receiveJS completionHandler:nil];
    }
    else if ([message.name isEqualToString:@"send"])
    {
        NSDictionary *body = message.body;
        if(!body) return;
        
        if ([body isKindOfClass:[NSDictionary class]])
        {
            if (body.count > 0)
            {
                //AAAA04F7010101
                NSString * firstArg = [body objectForKey:@"type"];

                if (self.bluetoothState == 0) {
                    if (![firstArg isEqualToString:@"查询"]) {
                        [self promoteTitle:NSLocalizedString(@"open_bluetooth", nil) Message:NSLocalizedString(@"bluetooth_trun_off_desc1", nil)];
                    }
                    return ;
                }
                
                if (self.bluetoothConnectState == 0) {//未连接蓝牙
                    if (![firstArg isEqualToString:@"查询"]) {
                        [self promoteTitle:NSLocalizedString(@"connect_bluetooth", nil) Message:NSLocalizedString(@"bluetooth_disconnect_desc", nil)];
                    }
                    return ;
                }
                if (body.count == 3) 
                {
                    
                    __block NSString * obj1 = [body objectForKey:@"type"];
                    self.deviceModel.functionName = obj1;
                    NSString * obj2 = [body objectForKey:@"code"];
                    self.deviceModel.functionCode = obj2;
                    NSString * obj3 = [body objectForKey:@"data"];
                    self.deviceModel.functionValue = obj3;
                    
                    NSString *command = @"";
                    
                    if ([self.characteristic.UUID.UUIDString isEqualToString:kCharacteristicOldUUID])
                    {
                        command = [self getFullDataWithCmd:obj2 value:obj3];
                    }
                    else if ([self.characteristic.UUID.UUIDString isEqualToString:kCharacteristicNewUUID])
                    {
                        command = [self getFullDataProtocolTwoWithCmd:obj2 func:obj3];
                    }
                    
                    self.deviceModel.downloadCommand = command;
                    
                    __block BOOL isFirst = YES;
                    
                    @weakify(self);
                    [self downBluetoothCommandString:command response:^(NSString *response) {
                        @strongify(self);
                        
                        DDLogDebug(@"功能:%@  下发指令:%@  返回数据:%@",obj1,command,response);
                        if (!isFirst)
                        {
                            obj1 = @"查询";
                        } 
                        else
                        {
                            isFirst = NO;
                        }
                        
                        NSString *receiveJS = [NSString stringWithFormat:@"window.receive('%@','%@')",obj1,response];
                        [self.webView evaluateJavaScript:receiveJS completionHandler:nil];
                    }];
                }
            }
        }
    }
}

  //老协议的数据组装
- (NSString *)getFullDataWithCmd:(NSString *)cmd value:(NSString *)value {
    // 计算长度并转换为十六进制
    NSInteger length = value.length / 2 + 3;
    NSString *len = [NSString stringWithFormat:@"%lx", (long)length];

    // 如果长度字符串长度小于2，前面补0
    if (len.length < 2) {
        len = [NSString stringWithFormat:@"0%@", len];
    }

    DDLogDebug(@"len = %@", len);

    // 返回拼接的完整命令
    return [NSString stringWithFormat:@"aaaa%@%@%@0101", len, cmd, value];
}


// 新协议的数据组装
- (NSString *)getFullDataProtocolTwoWithCmd:(NSString *)cmd func:(NSString *)func {
    
    NSString *frameHeader = @"55aa";
    NSString *version = @"00";
    NSString *cmdWork = @"06";
    NSString *dpLen = @"0005";
    
    // 计算dataLength，大端字节序
    NSUInteger dpLenLength = [dpLen length] / 2 + 3;
    NSString *dataLength = [NSString stringWithFormat:@"%04lx", (unsigned long)dpLenLength];
    
    NSString *funcLength = @"0001";

    // 计算校验和
    NSString *checksum = [self calculateChecksum:[NSString stringWithFormat:@"%@%@%@%@%@%@%@",
                                                  frameHeader, version, cmdWork, dataLength, cmd, funcLength, func]];

    // 拼接结果
    NSString *result = [NSString stringWithFormat:@"%@%@%@%@%@%@%@%@",
                        frameHeader, version, cmdWork, dataLength, cmd, funcLength, func, checksum];
    
    DDLogDebug(@"getFullDataProtocolTwo = %@", result);
    
    return result;
}

- (NSString *)calculateChecksum:(NSString *)data {
    NSUInteger sum = 0;
    
    for (NSUInteger i = 0; i < [data length]; i += 2) {
        NSString *byteString = [data substringWithRange:NSMakeRange(i, 2)];
        unsigned int byteValue;
        [[NSScanner scannerWithString:byteString] scanHexInt:&byteValue];
        sum += byteValue;
    }
    
    return [NSString stringWithFormat:@"%02lx", sum % 256];
}


- (void)promoteTitle:(NSString *)title Message:(NSString *)message
{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"ok", nil) style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)connectBluetoothAccrodingPeripheralName:(NSString *)returnCode
{
    //停止扫描
    [self.baby cancelScan];
    for (NSMutableDictionary *item in self.peripheralDataArray) {
        NSString * code = [item objectForKey:@"code"];
        if ([returnCode isEqualToString:code]) {
            CBPeripheral *peripheral = [item objectForKey:@"peripheral"];
            self.currPeripheral = peripheral;
            [self connectBluetooth];
            DDLogDebug(@"js连接设备编号:%@",code);
            self.peripheralCode = code;
        }
    }
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"你想到更改的标题" message:message preferredStyle:UIAlertControllerStyleAlert];
     // 添加确定按钮
     UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
         // 当用户点击确定按钮时，调用completionHandler
         completionHandler();
     }];
     [alertController addAction:okAction];
     
     // 显示UIAlertController
     [self presentViewController:alertController animated:YES completion:nil];
}


- (void)dealloc
{
    [[self.webView configuration].userContentController removeScriptMessageHandlerForName:@"connectbt"];
    [[self.webView configuration].userContentController removeScriptMessageHandlerForName:@"getbtlist"];
    [[self.webView configuration].userContentController removeScriptMessageHandlerForName:@"send"];
    [[self.webView configuration].userContentController removeScriptMessageHandlerForName:@"getSystemLanguage"];
}


@end
